package com.nd.qa.shareplate.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class FileUtils {


	// public static List<File> fileList = new ArrayList<File>();
	public static void writeFile(File file, String content) {
		try {
			file.createNewFile();
			FileOutputStream writerStream = new FileOutputStream(file);    
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
//			FileWriter fw = new FileWriter(file.getAbsoluteFile());
//			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Map<String, File> checkAllFile(File rootFile) throws Exception {
		Map<String, File> fileList = new HashMap<String, File>();
		File[] fs = rootFile.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if (fs[i].isDirectory()) {
				fileList.putAll(checkAllFile(fs[i]));
			}
			if (fs[i].getAbsolutePath().contains(".json")) {
				String[] list = fs[i].getCanonicalPath().split("\\\\");
				String key = list[list.length-3] + list[list.length-2] + list[list.length-1];
				fileList.put(fs[i].getName(), fs[i]);
			}
		}
		return fileList;
	}

	public static String readFile(File file) {
		BufferedReader reader = null;
		String laststr = "";
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "utf-8"));
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				laststr += temp;
				// System.out.println(laststr);
			}
			reader.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return laststr;
	}

	public static JSONObject parserJson(String data) {
		try {
			// ObjectMapper mapper = new ObjectMapper();
			// JsonNode rootNode = mapper.readTree(data);
			//
			// return rootNode;
			return JSONObject.fromObject(data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("��ЧJSON��ʽ����");
			e.printStackTrace();
		}
		return null;
	}

	public static String checkJson(String data){
		String jsonData = data;
		if (jsonData.charAt(0) == '[') {
			jsonData = String.format("{\"build\":%s}", jsonData);
		}
		return jsonData;
	}
	
	public static JSONObject convertJson(JSONObject source){
		JSONObject sourceJson = new JSONObject();
		for (Iterator<String> it = source.keys(); it.hasNext();) {
			String key = (String) it.next();
			JSONObject data = source.getJSONObject(key);
			key = source.getJSONObject(key).getString("page_name");
			sourceJson.put(key, data);
		}
		return sourceJson;
	}
	
	public static JSONObject covertBuildJson(JSONObject source){
		JSONObject sourceJson = new JSONObject();
		JSONArray buildJson = source.getJSONArray("build");
		for (int i = 0; i < buildJson.size(); i++) {
			JSONObject object = (JSONObject)buildJson.get(i);
			String key = object.getJSONObject("component").getString("name");
			//System.out.println(key);
			sourceJson.put(key, object);
		}
		return sourceJson;
	}
	
	public static String xmlToJson(String content) {
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setSkipNamespaces(true);
		xmlSerializer.setTypeHintsCompatibility(false);
		xmlSerializer.setTypeHintsEnabled(false);
		JSONObject jsonObject = (JSONObject) xmlSerializer.read(content);
		String jsonData = jsonObject.toString();
		jsonData = jsonData.replaceAll("\"@", "\"");
		// System.out.println(jsonData);
		return jsonData;
	}

	public static void extractDataToBuild(String content, File sourceBuildFile) {
		String sourceData = FileUtils.readFile(sourceBuildFile);
		sourceData = FileUtils.checkJson(sourceData);
		JSONObject sourceBuildJson = JSONObject.fromObject(sourceData);
		JSONArray buildList = sourceBuildJson.getJSONArray("build");
	
		JSONObject json = FileUtils.parserJson(content);
		JSONObject build_part = new JSONObject();
		Map<String, String> node = new HashMap<String, String>();
		node.put("name", json.getString("name"));
		node.put("namespace", json.getString("namespace"));
		build_part.put("component", node);

		Map<String, Object> propertiesMap = new HashMap<String, Object>();
		List<Object> group_list = new ArrayList<Object>();
		JSONObject group = json.getJSONObject("properties").getJSONObject(
				"group");
		JSONArray group_properties = group.getJSONArray("property");
		JSONArray properties = json.getJSONObject("properties").getJSONArray(
				"property");
		for (int i = 0; i < properties.size(); i++) {
			JSONObject property = (JSONObject) properties.get(i);
			propertiesMap.put(property.getString("name"),
					property.getString("value"));
		}

		Map<String, Object> groupPropertiesMap = new HashMap<String, Object>();
		for (int i = 0; i < group_properties.size(); i++) {
			JSONObject property = (JSONObject) group_properties.get(i);
			groupPropertiesMap.put(property.getString("name"),
					property.getString("value"));
		}
		group_list.add(groupPropertiesMap);
		propertiesMap.put(group.getString("name"), group_list);
		build_part.put("properties", propertiesMap);
		buildList.add(build_part);
		writeFile(new File("D:/build_part.json"), buildList.toString());
	}

	public static void extractDataToPage(String content, File sourcePageFile) {
		String sourceData = FileUtils.readFile(sourcePageFile);
		JSONObject sourcePageJson = JSONObject.fromObject(sourceData);
		for (Iterator<String> it = sourcePageJson.keys(); it.hasNext();) {
			String i = (String) it.next();
			//System.out.println(i);
		}
		
		JSONObject json = FileUtils.parserJson(content);
		JSONObject page_part = new JSONObject();
		String name = json.getString("name");
		String nameSpace = json.getString("namespace");

		JSONArray pages = json.getJSONArray("pages");
		for (int i = 0; i < pages.size(); i++) {
			JSONObject page = pages.getJSONObject(i);
			Map<String, Object> pageMap = new HashMap<String, Object>();
			Map<String, String> node = new HashMap<String, String>();
			node.put("name", json.getString("name"));
			node.put("namespace", json.getString("namespace"));

			String page_name = page.getString("name");

			Map<String, Object> propertiesMap = new HashMap<String, Object>();
			JSONObject group = page.getJSONObject("properties").getJSONObject(
					"group");
			JSONArray group_properties = group.getJSONArray("property");
			JSONArray properties = page.getJSONObject("properties")
					.getJSONArray("property");
			for (int j = 0; j < properties.size(); j++) {
				JSONObject property = (JSONObject) properties.get(j);
				propertiesMap.put(property.getString("name"),
						property.getString("value"));
			}

			List<Object> group_list = new ArrayList<Object>();
			Map<String, Object> groupPropertiesMap = new HashMap<String, Object>();
			for (int j = 0; j < group_properties.size(); j++) {
				JSONObject property = (JSONObject) group_properties.get(j);
				groupPropertiesMap.put(property.getString("name"),
						property.getString("value"));
			}
			group_list.add(groupPropertiesMap);
			propertiesMap.put(group.getString("name"), group_list);

			int template = page.get("template") == null ? -1 : Integer
					.parseInt(page.getString("template"));

			if (template == 1) {
				String title = String.format("%s://%s.%s/%s",
						page.getString("type"), nameSpace, name, page_name);
				Long randomNum = System.currentTimeMillis();
				pageMap.put("component", node);
				pageMap.put("page_name", page_name);
				pageMap.put("properties", propertiesMap);
				pageMap.put("template", title + "?pageid=" + randomNum);
				page_part.put(randomNum, pageMap);
			} else {
				// {page��type}/{component�ڵ��namespace}.{component�ڵ��name}/{page��name}:{
				String title = String.format("%s://%s.%s/%s",
						page.getString("type"), nameSpace, name, page_name);
				pageMap.put("component", node);
				pageMap.put("page_name", page_name);
				pageMap.put("properties", propertiesMap);
				pageMap.put("template", title);
				page_part.put(title, pageMap);
			}
		}
		for (Iterator<String> it = sourcePageJson.keys(); it.hasNext();) {
			String key = (String) it.next();
			page_part.put(key, sourcePageJson.get(key));
		}
		writeFile(new File("D:/page_part.json"), page_part.toString());
	}

	// public static void main(String[] args) throws Exception{
	// File root = new File(checkPath);
	// List<File> fileList = checkAllFile(root);
	// File test = fileList.get(0);
	// System.out.println(test.getAbsolutePath());
	// String fileStr = readFile(test);
	// parserJson(fileStr);
	//
	// }
}
